package com.web.wefun.controller;

import cn.dsna.util.images.ValidateCode;
import com.web.wefun.common.Const;
import com.web.wefun.util.PhoneCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Controller
@RequestMapping("/sys")
public class SysController {

    /*人机验证码的两个方法*/
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        ValidateCode vc = new ValidateCode(120, 30, 4, 100);
        //1 记录验证码
        String code = vc.getCode();
        System.out.println("验证码是:" + code);
        session.setAttribute(Const.VALI_CODE, code);
        //2 写出图片
        vc.write(response.getOutputStream());
    }

    @RequestMapping("/checkCode")
    @ResponseBody
    public String checkCode(String code, HttpSession session) {
        //判断用户提交的验证码是否为null或者长度是否为4位
        if (code != null && code.length() == 4) {
            String attribute = (String) session.getAttribute(Const.VALI_CODE);
            //忽略大小写比较验证码是否正确
            if (code.equalsIgnoreCase(attribute)) {
                return "OK";
            }
        }
        return "ERROR";
    }

    /*手机短信验证的两个方法*/
    @RequestMapping("/checkPhoneCode")
    @ResponseBody
    public String checkPhoneCode(String code, HttpSession session) {
        //判断用户提交的验证码是否为null或者长度是否为4位
        if (code != null && code.length() == 4) {
            String attribute = (String) session.getAttribute(Const.PHONE_CODE);
            //忽略大小写比较验证码是否正确
            if (code.equalsIgnoreCase(attribute)) {
                return "OK";
            }
        }
        return "NOOK";
    }

    @RequestMapping("/getPhoneCode")
    @ResponseBody
    public String getPhoneCode(String phone, HttpSession session) {
        System.out.println(phone);
        if (phone != null && phone.length() == 11) {
            //调用工具方法发送 验证码的短信
            String code = PhoneCodeUtil.getCode(phone);
            //把生成的验证码 保存到session当中
            session.setAttribute(Const.PHONE_CODE, code);
        }
        return "";
    }

}
